    //
//  ViewController.m
//  iMoc
//
//  Created by 微我网络 on 15/1/10.
//  Copyright (c) 2015年 lamcelot. All rights reserved.
//

#import "ChartViewController.h"
//#import "ActiveCircleView.h"
#import "CustomChartView.h"
#import "ChartDataView.h"
#import "CalendarPicker.h"
#import <AFNetworking.h>
#import "NewSportNetworking.h"
#import "OCCalendarViewController.h"
#import "UIImage+ImageEffects.h"
#import <DateTools.h>
#import "MPPlot.h"
//#import "Kal.h"

#import "SRSleep+Cate.h"
#import "SRDB.h"
#import "SRManager.h"
#import "Utils.h"
#import "SRSportNetService.h"
#import "SRSportNetSource.h"
#import "SRAccountNetService.h"
#import "SRMe.h"
#import "SRMe+Cate.h"

typedef NS_ENUM(NSInteger, DataCenterType) {
    
    DataCenterTypeAmount,
    DataCenterTypeSleep
};

@interface ChartViewController () <UIGestureRecognizerDelegate,OCCalendarDelegate>

@property (nonatomic) DataCenterType type;
@property (nonatomic,strong) UIImageView *nav;
@property (nonatomic,strong) UIImageView *backGround;
@property (nonatomic,strong) UISegmentedControl *segment;
@property (nonatomic,strong) CustomChartView *chart;
@property (nonatomic,strong) ChartDataView *data;

@property (nonatomic,strong) UIView *blur;
@property (nonatomic,strong) OCCalendarViewController *calendar;
@property (nonatomic,strong) CalendarPicker *picker;
//@property (nonatomic,strong) KalViewController *kal;

//@property (nonatomic,strong) ChartDataView *chart;
//@property (nonatomic,strong) UIScrollView *backGroundScrollView;
//@property (nonatomic,strong) UIView *backGroundContentViewDay;
//@property (nonatomic,strong) UIView *backGroundContentViewNight;

@property (nonatomic,strong) NSMutableDictionary *info;
@property (nonatomic,strong) NSArray *stepsInfo;

@property (nonatomic,strong) NSDate *selectedDate;
@property (nonatomic,strong) NSDate *startDate;
@property (nonatomic,strong) NSDate *endDate;

@end

@implementation ChartViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
//    [self performSelector:@selector(search) withObject:nil afterDelay:1];
//    [self fakeLogin];
    _type = 0;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    self.view.backgroundColor = [UIColor whiteColor];

    _backGround = [[UIImageView alloc] initWithFrame:self.view.frame];
    _backGround.image = [UIImage imageNamed:@"ground_amount"];
    _backGround.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:_backGround];
    
//    [self getNetData];
    [self loadFakeNavigation];
    [self initializeuserInterface];
    [self getNetData];
}

- (void)fakeLogin {
    
    [[SRAccountNetService loginWithUserName:@"1388"
                                    userPwd:@"1388"]
//    [[SRAccountNetService loginWithUserName:@"15608020186" userPwd:@"123456"]
     subscribeNext:^(id x) {
         //登陆成功保存userToken
         SRMe *me = x;
         [Utils saveUserLoginToken:me];
         
         [SVProgressHUD showSuccessWithStatus:@"登录成功"];
         SRDevice * device = [SRDevice findDeviceForMe:[SRMe currentUser]];
         [[SRManager sharedInstance] setCurrentPeripheralName:device.name];
         
         /**
          *  must post after login success
          */
//         [self performSelector:@selector(search) withObject:nil afterDelay:1];
         
     } error:^(NSError *error) {
         
         [SVProgressHUD showErrorWithStatus:@"登陆失败"];
     }];
}


- (void)loadFakeNavigation {
    
    _nav = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
    _nav.image = [UIImage imageNamed:@"nav_amount"];
    _nav.userInteractionEnabled = YES;
    [self.view addSubview:_nav];
    
    UILabel *fakeTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
    fakeTitle.text = @"数据中心";
    fakeTitle.textAlignment = NSTextAlignmentCenter;
    fakeTitle.font = [UIFont boldSystemFontOfSize:20];
    fakeTitle.textColor = [UIColor whiteColor];
    fakeTitle.center = CGPointMake(_nav.center.x, CGRectGetMaxY(_nav.frame)-20);
    [_nav addSubview:fakeTitle];
    
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    [back setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    back.frame = CGRectMake(0, 24, 60, 40);
    back.imageEdgeInsets = UIEdgeInsetsMake(10, 15, 10, 34);
    [back addTarget:self action:@selector(popPrevious) forControlEvents:UIControlEventTouchUpInside];
    [_nav addSubview:back];
    
    UIButton *moon = [UIButton buttonWithType:UIButtonTypeCustom];
    [moon setImage:[UIImage imageNamed:@"moon1"] forState:UIControlStateNormal];
    moon.frame = CGRectMake(CGRectGetMaxX(_nav.frame)-60, 24, 60, 40);
    [moon addTarget:self action:@selector(VCTypeChange:) forControlEvents:UIControlEventTouchUpInside];
    moon.imageEdgeInsets = UIEdgeInsetsMake(10, 20, 10, 20);
    [_nav addSubview:moon];
}

- (void)popPrevious {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)VCTypeChange:(UIButton *)sender {
    
    if (_type == DataCenterTypeAmount) {
        [sender setImage:[UIImage imageNamed:@"walk"] forState:UIControlStateNormal];
        _nav.image = [UIImage imageNamed:@"nav_sleep"];
        _backGround.image = [UIImage imageNamed:@"ground_sleep"];
        _chart.style = ChartViewStyleSleep;
        _data.style = _segment.selectedSegmentIndex +3;
        _type = DataCenterTypeSleep;
        _chart.graph.type = _data.style;
    }
    else if (_type == DataCenterTypeSleep) {
        [sender setImage:[UIImage imageNamed:@"moon1"] forState:UIControlStateNormal];
        _nav.image = [UIImage imageNamed:@"nav_amount"];
        _backGround.image = [UIImage imageNamed:@"ground_amount"];
        _chart.style = ChartViewStyleAmount;
        _data.style = _segment.selectedSegmentIndex;
        _type = DataCenterTypeAmount;
        _chart.graph.type = _data.style;
    }
    [self getNetData];
}

- (void)initializeuserInterface {
    
    _segment = [[UISegmentedControl alloc] initWithItems:@[@"日",@"周",@"月"]];
    _segment.frame = CGRectMake(7, 82, self.view.frame.size.width-14, 28);
    _segment.tintColor = [UIColor colorWithRed:144/255.f green:87/255.f blue:192/255.f alpha:1];
    [_segment setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} forState:UIControlStateNormal];
    [_segment setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16],
                                      NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateSelected];
    _segment.selectedSegmentIndex = 0;
    [_segment addTarget:self action:@selector(didSelectSegment:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_segment];
    
    _chart = [[CustomChartView alloc] initWithFrame:CGRectMake(7, 130, self.view.frame.size.width-14, 150)
                                              style:ChartViewStyleAmount];
    [self.view addSubview:_chart];
    
    _data = [[ChartDataView alloc] initWithFrame:CGRectMake(0, 300, self.view.frame.size.width, 160)];
    [self.view addSubview:_data];
    _data.style = ChartDataViewStyleAmountDay;
    
    _picker = [[CalendarPicker alloc] initWithFrame:CGRectMake(self.view.frame.size.width/5, self.view.frame.size.height-40, self.view.frame.size.width/5*3, 40)];
    [_picker.next addTarget:self action:@selector(selectNext) forControlEvents:UIControlEventTouchUpInside];
    _picker.next.hidden = YES;
    [_picker.previous addTarget:self action:@selector(selectPrevious) forControlEvents:UIControlEventTouchUpInside];
    _picker.dateLabel.userInteractionEnabled = YES;
    NSDate *today = [NSDate date];
    if ([today isToday]) {
        today = [today dateBySubtractingDays:1];
    }
    _picker.dateLabel.text = [today formattedBy_yyyyMMdd];
    [self.view addSubview:_picker];
    
    UITapGestureRecognizer *tap0 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(appear)];
    [_picker.dateLabel addGestureRecognizer:tap0];
    
    //    ActiveCircleView *circle = [[ActiveCircleView alloc] initWithCenter:self.view.center
    //                                                                  width:200
    //                                                              ringWidth:8
    //                                                                  style:ActiveCircleStyleBlur];
    //    circle.ringColor = [UIColor redColor];
    //    [self.view addSubview:circle];
    //    [circle startAnimationWithAngle:360];
    
//    _kal = [[KalViewController alloc] initWithSelectionMode:KalSelectionModeSingle];
//    _kal.beginDate = [NSDate dateStartOfDay:[NSDate date]];
//    _kal.endDate = [NSDate dateStartOfDay:[[NSDate date] offsetDay:1]];
//    [self.view addSubview:[_kal calendarView]];
    
    _blur = [[UIView alloc] initWithFrame:self.view.frame];
    _blur.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.8];
    _blur.userInteractionEnabled = YES;
    _blur.alpha = 0;
    [self.view addSubview:_blur];
    
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss)];
//    [_blur addGestureRecognizer:tap];
    
    _calendar = [[OCCalendarViewController alloc] initAtPoint:CGPointMake(CGRectGetMidX(self.view.frame)+7,CGRectGetMaxY(self.view.frame)-300)
                                                       inView:self.view
                                                arrowPosition:OCArrowPositionNone
                                                selectionMode:OCSelectionSingleDate];
    _calendar.delegate = self;
    [_blur addSubview:_calendar.view];
    
    [_calendar setStartDate:[[NSDate date] dateBySubtractingDays:1]];
    [_calendar setEndDate:[[NSDate date] dateBySubtractingDays:1]];
    
    _startDate = [[NSDate date] dateBySubtractingDays:1];
    _endDate   = [[NSDate date] dateBySubtractingDays:1];
    
    UIButton *cancle = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancle setTitle:@"取消" forState:UIControlStateNormal];
    [cancle setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    cancle.bounds = CGRectMake(0, 0, 200, 30);
    cancle.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMaxY(self.view.frame)-20);
    cancle.titleLabel.textAlignment = NSTextAlignmentCenter;
    [cancle addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
    [_blur addSubview:cancle];
}

- (void)selectNext {
    
    NSString *string;
    switch (_segment.selectedSegmentIndex) {
        case 0: {
            _startDate = [_startDate dateByAddingDays:1];
            if ([_startDate isToday]) {
                _startDate = [_startDate dateBySubtractingDays:1];
                _picker.next.hidden = YES;
            }
            else {
                _picker.next.hidden = NO;
            }
            _endDate   = _startDate;
            string = [_startDate formattedBy_yyyyMMdd];
        }break;
            
        case 1: {
            _startDate = [_startDate dateByAddingWeeks:1];
            NSArray *array = [_startDate weekStartAndweekEndDate];
            _startDate = (NSDate *)[array firstObject];
            _endDate   = (NSDate *)[array lastObject];
            if ([_endDate isToday]) {
                _endDate = [_endDate dateBySubtractingDays:1];
                _picker.next.hidden = YES;
            }
            else {
                _picker.next.hidden = NO;
            }
            string = [NSString stringWithFormat:@"%@～%@",[_startDate formattedBy_M_d],[_endDate formattedBy_M_d]];
        }break;
            
        case 2: {
            _startDate = [_startDate dateByAddingMonths:1];
            NSArray *array = [_startDate monthStartAndmonthEndDate];
            _startDate = [array firstObject];
            _endDate   = [array lastObject];
            if ([_endDate isToday]) {
                _endDate = [_endDate dateBySubtractingDays:1];
                _picker.next.hidden = YES;
            }
            else {
                _picker.next.hidden = NO;
            }
            string = [NSString stringWithFormat:@"%@",[_startDate formattedBy_yyyyMM]];
        }break;
            
        default:
            break;
    }
    NSLog(@"%@",string);
    [_calendar setSelectionMode:OCSelectionDateRange];
    [_calendar setEndDate:_endDate];
    [_calendar setStartDate:_startDate];
    [_calendar setSelectionMode:OCSelectionSingleDate];
    _picker.dateLabel.text = string;
    [self getNetData];
}

- (void)selectPrevious {
    
    NSString *string;
    switch (_segment.selectedSegmentIndex) {
        case 0:
            _startDate = [_startDate dateBySubtractingDays:1];
            _endDate   = _startDate;
            string = [_startDate formattedBy_yyyyMMdd];
            break;
            
        case 1: {
            _startDate = [_startDate dateBySubtractingWeeks:1];
            NSArray *array = [_startDate weekStartAndweekEndDate];
            _startDate = (NSDate *)[array firstObject];
            _endDate   = (NSDate *)[array lastObject];
            string = [NSString stringWithFormat:@"%@～%@",[_startDate formattedBy_M_d],[_endDate formattedBy_M_d]];
        }break;
            
        case 2: {
            _startDate = [_startDate dateBySubtractingMonths:1];
            NSArray *array = [_startDate monthStartAndmonthEndDate];
            _startDate = [array firstObject];
            _endDate   = [array lastObject];
            string = [NSString stringWithFormat:@"%@",[_startDate formattedBy_yyyyMM]];
        }break;
            
        default:
            break;
    }
    NSLog(@"%@",string);
    
    _picker.next.hidden = NO;
    [_calendar setSelectionMode:OCSelectionDateRange];
    [_calendar setEndDate:_endDate];
    [_calendar setStartDate:_startDate];
    [_calendar setSelectionMode:OCSelectionSingleDate];
    _picker.dateLabel.text = string;
    [self getNetData];
}

- (void)completedWithStartDate:(NSDate *)startDate endDate:(NSDate *)endDate {
    
    NSLog(@"%@---%@",startDate,endDate);
    NSString *string;
    switch (_segment.selectedSegmentIndex) {
        case 0:
            _startDate = startDate;
            if ([_startDate isToday]) {
                _startDate = [_startDate dateBySubtractingDays:1];
            }
            _endDate = _startDate;
            string = [startDate formattedBy_yyyyMMdd];
            break;
            
        case 1: {
            NSArray *array = [startDate weekStartAndweekEndDate_CHN];
            _startDate = [(NSDate *)[array firstObject] dateBySubtractingSeconds:1];
            _endDate   = [(NSDate *)[array lastObject]  dateBySubtractingSeconds:1];
            if ([_endDate isToday]) {
                _endDate = [_endDate dateBySubtractingDays:1];
            }
            string = [NSString stringWithFormat:@"%@～%@",[_startDate formattedBy_M_d],[_endDate formattedBy_M_d]];
        }break;
            
        case 2: {
            NSArray *array = [startDate monthStartAndmonthEndDate];
            _startDate = [array firstObject];
            _endDate   = [array lastObject];
            if ([_endDate isToday]) {
                _endDate = [_endDate dateBySubtractingDays:1];
            }
            string = [NSString stringWithFormat:@"%@",[_startDate formattedBy_yyyyMM]];
        }break;
            
        default:
            break;
    }
    NSLog(@"%@",string);
    
    _picker.next.hidden = NO;
    [_calendar setSelectionMode:OCSelectionDateRange];
    [_calendar setEndDate:_endDate];
    [_calendar setStartDate:_startDate];
    [_calendar setSelectionMode:OCSelectionSingleDate];
    _picker.dateLabel.text = string;
    [self getNetData];
}

- (void)dismiss {
    
    [UIView animateWithDuration:0.3 animations:^{
        _blur.alpha = 0;
    } completion:^(BOOL finished) {
        if (finished) {
        }
    }];
}

- (void)appear {
    
    [UIView animateWithDuration:0.6 animations:^{
        _blur.alpha = 1;
    }];
}

- (void)getNetData {
    
    switch (_data.style) {
            
        case 0: {
            
            [NewSportNetworking getRecordWithDate:[_startDate formattedBy_yyyyMMdd] success:^(NSArray *array) {
                
                CGFloat value0 = 0,value1 = 0,value2 = 0;
                NSMutableArray *values = [NSMutableArray array];
                NSMutableArray *titles = [NSMutableArray array];
                for (NSDictionary *section in array) {
                    [values addObject:[NSString stringWithFormat:@"%@",section[@"walkCounter"]]];
                    [titles addObject:[NSString stringWithFormat:@"%ld",[section[@"section"] integerValue]*2]];
                    value0 += [section[@"calorie"] floatValue];
                    value1 += [section[@"mileage"] floatValue]/5000000;
                    value2 += [section[@"walkCounter"] floatValue];
                }
                if (!values.count) {
                    [values addObject:@"0"];
                }
                
                _chart.value = [NSString stringWithFormat:@"%.0f",value2];
                _chart.values = values;
                _chart.xTitle = titles;
                _data.string0 = [NSString stringWithFormat:@"%.0f",value0];
                _data.string1 = [NSString stringWithFormat:@"%.0f",value1];
                
//                _data.string3 = @"0";
//                _data.string4 = @"0";
//                _data.string5 = @"0";
                [NewSportNetworking getTaskWithDate:[_startDate formattedBy_yyyyMMdd] success:^(NSDictionary *dictionary) {
                    
                    if (dictionary[@"totalCounter"]) {
                        _data.string2 = [NSString stringWithFormat:@"%@",dictionary[@"totalCounter"]];
                    }
                    else {
                        _data.string2 = @"0";
                    }
                } fail:^(NSError *error) {
                    
                }];
            } fail:^(NSError *error) {
                
            }];
        }break;
            
        case 1:
            
        case 2: {
            
            [NewSportNetworking getRecordsWithStart:[_startDate formattedBy_yyyyMMdd] end:[_endDate formattedBy_yyyyMMdd] success:^(NSArray *array) {
                
                __block CGFloat value3 = 0,value4 = 0,value5 = 0;
                __block NSInteger aimed = 0;
                NSMutableArray *values = [NSMutableArray array];
                NSMutableArray *titles = [NSMutableArray array];
                for (NSDictionary *perDay in array) {
                    [values addObject:perDay[@"walkCounter"]];
                    NSString *create = perDay[@"createDate"];
                    [titles addObject:[create substringFromIndex:create.length - 5]];
//                    if (perDay[@"createDate"]) {
//                        NSString *str = [NSString stringWithFormat:@"%@",perDay[@"createDate"]];
//                        str = [str substringFromIndex:str.length-5];
//                        [titles addObject:str];
//                    }
                    
                    value5 += [perDay[@"calorie"] integerValue];
                    value4 += [perDay[@"mileage"] floatValue]/5000000;
                    value3 += [perDay[@"walkCounter"] integerValue];
                }
                if (!values.count) {
                    [values addObject:@(0)];
                }
                
                _chart.value  = [NSString stringWithFormat:@"%.0f",value3];
                _chart.values = values;
                _chart.xTitle = titles;
                
                _data.string0 = [NSString stringWithFormat:@"%.0f",value3/values.count];
                _data.string1 = [NSString stringWithFormat:@"%.1f",value4/values.count];
                _data.string2 = [NSString stringWithFormat:@"%.1f",value5/values.count];
                
                _data.string4 = [NSString stringWithFormat:@"%.0f",value4];
                _data.string5 = [NSString stringWithFormat:@"%.0f",value5];
                
                [NewSportNetworking getTasksWithStart:[_startDate formattedBy_yyyyMMdd] end:[_endDate formattedBy_yyyyMMdd] success:^(NSArray *array) {
                    
                    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                        NSDictionary *dic = (NSDictionary *)obj;
                        NSInteger maxIdx = MIN(idx, _chart.graph.buttons.count-1);
                        UIButton *button = _chart.graph.buttons[maxIdx];
                        if ([dic[@"completedCounter"] integerValue] < [dic[@"totalCounter"] integerValue]) {
                            //未完成
//                            button.layer.borderColor = [UIColor redColor].CGColor;
                            [(CALayer *)[button.layer.sublayers lastObject] setBorderColor:[UIColor redColor].CGColor];
                        }
                        else {
//                            button.layer.borderColor = [UIColor greenColor].CGColor;
                            [(CALayer *)[button.layer.sublayers lastObject] setBorderColor:[UIColor greenColor].CGColor];
                            aimed += 1;
                        }
                    }];
                    _data.string3 = [NSString stringWithFormat:@"%ld",(long)aimed];
                } fail:^(NSError *error) {
                }];
            } fail:^(NSError *error) {
            }];
        }break;
            
        case 3: {
            [NewSportNetworking getSleepRecordWithDate:[_startDate formattedBy_yyyyMMdd] success:^(NSDictionary *data) {
                
                NSArray *count = data[@"count"];
                
                int deep   = [SRSleep minutesOfDeepSleepForArray:count];
                int light  = [SRSleep minutesOfLightSleepForArray:count];
                int active = [SRSleep minutesOfActiveSleepForArray:count];
                
//                count = [SRSleep getSortedArrayWithArray:count];
                NSMutableArray *values = [NSMutableArray array];
                NSMutableArray *titles = [NSMutableArray array];
                [count enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                    NSDictionary *dic = (NSDictionary *)obj;
                    [values addObject:dic[@"shake"]];
                    NSString *time = dic[@"time"]?dic[@"time"]:@"";
                    
                    NSDate *timeDate = [NSDate dateFromString:time format:@"yyyy-MM-dd HH:mm:ss"];
                    
                    
                    
                    [titles addObject:[NSDate stringFromDate:timeDate format:@"HH:mm"]];
                }];
                if (!values.count) {
                    [values addObject:@(0)];
                }
                
                NSDate *start = [NSDate dateFromString:data[@"startTime"] format:@"yyyy-MM-dd HH:mm:ss"];
                NSDate *end   = [NSDate dateFromString:data[@"endTime"] format:@"yyyy-MM-dd HH:mm:ss"];
                NSTimeInterval minutesInterval = fabs([end timeIntervalSinceDate:start]/60);
                
                _chart.value = [NSString stringWithFormat:@"%.0f",minutesInterval];
                _chart.values = values;
                _chart.xTitle = titles;
                
                _data.string0 = [NSString stringWithFormat:@"%d",deep];
                _data.string1 = [NSString stringWithFormat:@"%d",light];
                _data.string2 = [NSString stringWithFormat:@"%d",active];
                _data.string3 = [start formattedBy_hhmm];
                _data.string4 = [end formattedBy_hhmm];
                
            } fail:^(NSError *error) {
                
            }];
        }break;
            
        case 4:
        case 5: {
            
            [NewSportNetworking getSleepRecordsWithStart:[_startDate formattedBy_yyyyMMdd] end:[_endDate formattedBy_yyyyMMdd] success:^(NSArray *array) {
                
                NSMutableArray *values = [NSMutableArray array];
                NSMutableArray *titles = [NSMutableArray array];
                __block CGFloat value0 = 0,value1 = 0,value2 = 0;
                [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                    NSDictionary *dic = (NSDictionary *)obj;
                    NSDate *start = [NSDate dateFromString:dic[@"startTime"] format:@"yyyy-MM-dd HH:mm:ss"];
                    NSDate *end   = [NSDate dateFromString:dic[@"endTime"] format:@"yyyy-MM-dd HH:mm:ss"];
                    NSTimeInterval minutesInterval = fabs([end timeIntervalSinceDate:start]/60);
                    [values addObject:@(minutesInterval)];
                    [titles addObject:[start formattedBy_M_d]];
                    
                    value0 += minutesInterval;
                    if (minutesInterval > 480) {
                        value1 ++;
                    }
                    else {
                        value2 ++;
                    }
                }];
                if (!values.count) {
                    [values addObject:@(0)];
                }
                
                _chart.value = [NSString stringWithFormat:@"%.0f",value0];
                _chart.values = values;
                _chart.xTitle = titles;
                
                _data.string0 = [NSString stringWithFormat:@"%.0f",value0/MAX(1, array.count)];
                _data.string1 = [NSString stringWithFormat:@"%.0f",value1];
                _data.string2 = [NSString stringWithFormat:@"%.0f",value2];
                
            } fail:^(NSError *error) {
                
            }];
        }break;
            
        default:
            break;
    }
}

- (void)didSelectDate:(NSDate *)date {
    
    NSLog(@"%@",date);
    NSDate *theStart = [NSDate dateFromString:[NSString stringWithFormat:@"%04ld-%04ld-%04ld",(long)[[NSDate date] year],(long)[[NSDate date] month],(long)[[NSDate date] day]]];
    NSLog(@"%d",[date isLaterThanOrEqualTo:theStart]);
    if ([date isLaterThanOrEqualTo:theStart]) {
        [_calendar setStartDate:[[NSDate date] dateBySubtractingDays:1]];
        [_calendar setEndDate:[[NSDate date]   dateBySubtractingDays:1]];
        [self dismiss];
        return;
    }
    
    [_calendar.calView setSelectionMode:OCSelectionDateRange];
    switch (_segment.selectedSegmentIndex) {
            
        case 0: {
            [_calendar setStartDate:date];
            [_calendar setEndDate:date];
        }break;
            
        case 1: {
            NSArray *array = [date weekStartAndweekEndDate_CHN];
            NSDate *start = [(NSDate *)[array firstObject] dateBySubtractingSeconds:1];
            NSDate *end   = [(NSDate *)[array lastObject]  dateBySubtractingSeconds:1];
            [_calendar setStartDate:start];
            [_calendar setEndDate:end];
        }break;
            
        case 2: {
            NSArray *array = [date monthStartAndmonthEndDate];
            NSDate *start = (NSDate *)[array firstObject];
            NSDate *end   = (NSDate *)[array lastObject];
            [_calendar setStartDate:start];
            [_calendar setEndDate:end];
        }break;
            
        default:
            break;
    }
    [_calendar getDelegateData];
    [self dismiss];
    [_calendar.calView setSelectionMode:OCSelectionSingleDate];
}

- (void)didSelectSegment:(UISegmentedControl *)segment {
    
    if (_type == DataCenterTypeAmount) {
        _data.style = _segment.selectedSegmentIndex;
    }
    else if (_type == DataCenterTypeSleep) {
        _data.style = _segment.selectedSegmentIndex +3;
    }
    _chart.graph.type = _data.style;
    
    
    NSDate *now = [[NSDate date] dateBySubtractingDays:1];
    [_calendar setStartDate:now];
    [_calendar setEndDate:now];
    [_calendar getDelegateData];
    _picker.next.hidden = YES;
    [self getNetData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
